// AI服务API接口
export interface AiServiceResponse {
  code: number;
  message: string;
  data?: any;
}

export interface AiRequest {
  userId: number | string;
  input?: string;
  question?: string;
  query?: string;
  prompt?: string;
  message?: string;
  agentRole?: string;
}

export class AiService {
  private baseUrl: string;

  constructor(baseUrl: string = '') {
    this.baseUrl = baseUrl;
  }

  // 通用请求方法
  private async request(endpoint: string, data: any): Promise<AiServiceResponse> {
    try {
      console.log(`发送API请求: ${endpoint}`, data);

      // 创建AbortController用于超时控制
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 180000); // 3分钟超时

      const response = await fetch(`${this.baseUrl}${endpoint}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
        body: JSON.stringify(data),
        signal: controller.signal
      });

      clearTimeout(timeoutId);

      console.log(`API响应状态: ${response.status}`);

      if (!response.ok) {
        const errorText = await response.text();
        console.error(`API请求失败: ${response.status} - ${errorText}`);
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
      }

      const result = await response.json();
      console.log(`API响应结果:`, result);
      return result;
    } catch (error) {
      console.error('API请求异常:', error);

      // 处理超时错误
      if (error instanceof Error && error.name === 'AbortError') {
        throw new Error('请求超时，请稍后重试');
      }

      throw error;
    }
  }

  // 知识问答 - AI百科全书
  async knowledgeQA(userId: number | string, question: string): Promise<AiServiceResponse> {
    return this.request('/api/ai/miniprogram/knowledge/qa', {
      userId,
      question
    });
  }

  // 信息查询 - 天气电话资讯
  async informationQuery(userId: number | string, query: string): Promise<AiServiceResponse> {
    return this.request('/api/ai/miniprogram/info/query', {
      userId,
      query
    });
  }

  // 文本生成 - 创意写作助手
  async textGeneration(userId: number | string, prompt: string, type: string = 'general'): Promise<AiServiceResponse> {
    return this.request('/api/ai/miniprogram/text/generate', {
      userId,
      prompt,
      type
    });
  }

  // 智能翻译
  async translation(userId: number | string, text: string, fromLang: string = '中文', toLang: string = '英文'): Promise<AiServiceResponse> {
    return this.request('/api/ai/miniprogram/translate', {
      userId,
      text,
      fromLang,
      toLang
    });
  }

  // 智能翻译 - 流式输出
  async translationStream(
    userId: number | string,
    text: string,
    fromLang: string = '中文',
    toLang: string = '英文',
    onMessage: (content: string) => void,
    onComplete: () => void,
    onError: (error: any) => void
  ): Promise<void> {
    return this.processStream('/api/ai/miniprogram/translate/stream', {
      userId,
      text,
      fromLang,
      toLang
    }, onMessage, onComplete, onError);
  }

  // 情感陪伴
  async emotionalCompanion(userId: number | string, message: string): Promise<AiServiceResponse> {
    return this.request('/api/ai/miniprogram/emotion/companion', {
      userId,
      message
    });
  }

  // 智能推荐
  async recommendation(userId: number | string, preferences: string, category: string = '通用'): Promise<AiServiceResponse> {
    return this.request('/api/ai/miniprogram/recommend', {
      userId,
      preferences,
      category
    });
  }

  // 游戏娱乐
  async gameEntertainment(userId: number | string, gameType: string, userInput: string, gameState: string = 'start',
                         difficulty?: string, maxQuestions?: number, enableHints?: boolean, randomMode?: boolean): Promise<AiServiceResponse> {
    const requestData: any = {
      userId,
      gameType,
      userInput,
      gameState
    };

    // 添加可选配置参数
    if (difficulty) requestData.difficulty = difficulty;
    if (maxQuestions) requestData.maxQuestions = maxQuestions;
    if (enableHints !== undefined) requestData.enableHints = enableHints;
    if (randomMode !== undefined) requestData.randomMode = randomMode;

    return this.request('/api/ai/miniprogram/game/entertainment', requestData);
  }

  // 获取游戏会话信息
  async getGameSession(userId: number | string, gameType: string): Promise<AiServiceResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/api/ai/miniprogram/game/session/${userId}/${gameType}`, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error('获取游戏会话失败:', error);
      throw error;
    }
  }

  // 重置游戏会话
  async resetGameSession(userId: number | string, gameType: string): Promise<AiServiceResponse> {
    return this.request('/api/ai/miniprogram/game/session/reset', {
      userId,
      gameType
    });
  }

  // 使用游戏提示
  async useGameHint(userId: number | string, gameType: string): Promise<AiServiceResponse> {
    return this.request('/api/ai/miniprogram/game/hint', {
      userId,
      gameType
    });
  }

  // 调整游戏难度
  async adjustGameDifficulty(userId: number | string, gameType: string, difficulty: string): Promise<AiServiceResponse> {
    return this.request('/api/ai/miniprogram/game/difficulty', {
      userId,
      gameType,
      difficulty
    });
  }

  // 获取游戏统计
  async getGameStats(userId: number | string, gameType: string): Promise<AiServiceResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/api/ai/miniprogram/game/stats/${userId}/${gameType}`, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error('获取游戏统计失败:', error);
      throw error;
    }
  }

  // 健康管理
  async healthManagement(userId: number | string, healthData: string, analysisType: string = 'comprehensive'): Promise<AiServiceResponse> {
    return this.request('/api/ai/miniprogram/health/management', {
      userId,
      healthData,
      analysisType
    });
  }

  // 图片生成 - AI文生图
  async imageGeneration(userId: number | string, prompt: string, style: string = 'realistic', size: string = '1024x1024'): Promise<AiServiceResponse> {
    return this.request('/api/ai/miniprogram/image/generation', {
      userId,
      prompt,
      style,
      size
    });
  }

  // ==================== 流式输出API ====================

  // 通用流式处理方法
  private async processStream(
    endpoint: string,
    data: any,
    onMessage: (content: string) => void,
    onComplete: () => void,
    onError: (error: any) => void
  ): Promise<void> {
    return new Promise((resolve, reject) => {
      fetch(`${this.baseUrl}${endpoint}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
      }).then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body?.getReader();
        if (!reader) {
          throw new Error('Response body is null');
        }

        const decoder = new TextDecoder();
        let buffer = '';
        let currentEvent = '';

        const processStreamData = async () => {
          try {
            while (true) {
              const { done, value } = await reader.read();
              if (done) break;

              buffer += decoder.decode(value, { stream: true });
              const lines = buffer.split('\n');
              buffer = lines.pop() || '';

              for (const line of lines) {
                if (line.trim() === '') continue;

                console.log('🔍 处理SSE行:', line);

                if (line.startsWith('event:')) {
                  currentEvent = line.slice(6).trim();
                  console.log('📋 事件类型:', currentEvent);
                } else if (line.startsWith('data:')) {
                  const data = line.slice(5).trim();
                  console.log('📦 数据内容:', data);

                  if (currentEvent === 'data') {
                    try {
                      const parsed = JSON.parse(data);
                      console.log('✅ 解析成功:', parsed);

                      if (parsed.type === 'data' && parsed.content) {
                        if (typeof onMessage === 'function') {
                          onMessage(parsed.content);
                        }
                      }
                    } catch (e) {
                      console.warn('❌ 解析SSE数据失败:', e, '原始数据:', data);

                      // 尝试直接使用数据作为内容
                      if (data && data !== '[DONE]') {
                        try {
                          // 可能是直接的文本内容
                          if (typeof onMessage === 'function') {
                            onMessage(data);
                          }
                        } catch (directError) {
                          console.warn('直接使用数据也失败:', directError);
                        }
                      }
                    }
                  } else if (currentEvent === 'end' || data === '[DONE]') {
                    console.log('🏁 流式输出结束');
                    if (typeof onComplete === 'function') {
                      onComplete();
                    }
                    resolve();
                    return;
                  } else if (currentEvent === 'error') {
                    console.log('❌ 收到错误事件');
                    try {
                      const parsed = JSON.parse(data);
                      const error = new Error(parsed.message || '流式输出错误');
                      if (typeof onError === 'function') {
                        onError(error);
                      }
                      reject(error);
                    } catch (e) {
                      const error = new Error('流式输出错误');
                      if (typeof onError === 'function') {
                        onError(error);
                      }
                      reject(error);
                    }
                    return;
                  } else {
                    // 没有明确的事件类型，尝试解析数据
                    console.log('🤔 未知事件类型，尝试直接解析数据');
                    try {
                      const parsed = JSON.parse(data);
                      if (parsed.content || parsed.response || parsed.data) {
                        const content = parsed.content || parsed.response || parsed.data;
                        if (typeof onMessage === 'function') {
                          onMessage(content);
                        }
                      }
                    } catch (e) {
                      // 可能是纯文本
                      if (data && typeof onMessage === 'function') {
                        onMessage(data);
                      }
                    }
                  }
                } else {
                  // 处理其他格式的SSE数据
                  console.log('🔄 处理非标准SSE格式:', line);

                  // 检查是否包含JSON数据
                  if (line.includes('{') && line.includes('}')) {
                    // 尝试提取JSON部分
                    const jsonStart = line.indexOf('{');
                    const jsonEnd = line.lastIndexOf('}') + 1;
                    if (jsonStart >= 0 && jsonEnd > jsonStart) {
                      const jsonStr = line.slice(jsonStart, jsonEnd);
                      try {
                        const parsed = JSON.parse(jsonStr);
                        console.log('🎯 提取JSON成功:', parsed);

                        if (parsed.type === 'data' && parsed.content) {
                          if (typeof onMessage === 'function') {
                            onMessage(parsed.content);
                          }
                        } else if (parsed.content || parsed.response || parsed.data) {
                          const content = parsed.content || parsed.response || parsed.data;
                          if (typeof onMessage === 'function') {
                            onMessage(content);
                          }
                        }
                      } catch (e) {
                        console.warn('JSON提取失败:', e, '原始行:', line);
                      }
                    }
                  } else if (line.includes('data:')) {
                    const dataStart = line.indexOf('data:') + 5;
                    const data = line.slice(dataStart).trim();
                    try {
                      const parsed = JSON.parse(data);
                      if (parsed.content || parsed.response) {
                        const content = parsed.content || parsed.response;
                        if (typeof onMessage === 'function') {
                          onMessage(content);
                        }
                      }
                    } catch (e) {
                      if (data && typeof onMessage === 'function') {
                        onMessage(data);
                      }
                    }
                  } else {
                    // 可能是纯文本内容
                    const trimmedLine = line.trim();
                    if (trimmedLine && typeof onMessage === 'function') {
                      onMessage(trimmedLine);
                    }
                  }
                }
              }
            }

            if (typeof onComplete === 'function') {
              onComplete();
            }
            resolve();
          } catch (error) {
            console.error('流式处理错误:', error);
            if (typeof onError === 'function') {
              onError(error);
            }
            reject(error);
          }
        };

        processStreamData();

      }).catch(error => {
        console.error('启动流式输出失败:', error);
        if (typeof onError === 'function') {
          onError(error);
        }
        reject(error);
      });
    });
  }

  // 知识问答 - 流式输出 (参考React版本使用EventSource)
  async knowledgeQAStream(userId: number | string, question: string, onMessage: (content: string) => void, onComplete: () => void, onError: (error: any) => void): Promise<void> {
    return this.processStream('/api/ai/miniprogram/knowledge/qa/stream', {
      userId,
      question
    }, onMessage, onComplete, onError);
  }
  // 旧的重复实现已删除，现在使用通用的processStream方法

  // 信息查询 - 流式输出
  async informationQueryStream(
    userId: number | string,
    query: string,
    mode: string,
    onMessage: (content: string) => void,
    onComplete: () => void,
    onError: (error: any) => void
  ): Promise<void> {
    return this.processStream('/api/ai/miniprogram/info/query/stream', {
      userId,
      query,
      mode
    }, onMessage, onComplete, onError);
  }



  // 游戏娱乐 - 流式输出
  async gameEntertainmentStream(
    userId: number | string,
    gameType: string,
    userInput: string,
    gameState: string = 'start',
    difficulty?: string,
    maxQuestions?: number,
    enableHints?: boolean,
    randomMode?: boolean,
    onMessage?: (content: string) => void,
    onComplete?: () => void,
    onError?: (error: any) => void
  ): Promise<void> {
    const requestData: any = {
      userId,
      gameType,
      userInput,
      gameState
    };

    // 添加可选配置参数
    if (difficulty) requestData.difficulty = difficulty;
    if (maxQuestions) requestData.maxQuestions = maxQuestions;
    if (enableHints !== undefined) requestData.enableHints = enableHints;
    if (randomMode !== undefined) requestData.randomMode = randomMode;

    return this.processStream('/api/ai/miniprogram/game/entertainment/stream', requestData,
                             onMessage || (() => {}), onComplete || (() => {}), onError || (() => {}));
  }

  // 健康管理 - 流式输出
  async healthManagementStream(
    userId: number | string,
    healthData: string,
    analysisType: string = 'comprehensive',
    onMessage: (content: string) => void,
    onComplete: () => void,
    onError: (error: any) => void
  ): Promise<void> {
    return this.processStream('/api/ai/miniprogram/health/management/stream', {
      userId,
      healthData,
      analysisType
    }, onMessage, onComplete, onError);
  }

  // 文本生成 - 流式输出
  async textGenerationStream(
    userId: number | string,
    prompt: string,
    onMessage: (content: string) => void,
    onComplete: () => void,
    onError: (error: any) => void
  ): Promise<void> {
    return this.processStream('/api/ai/miniprogram/text/generate/stream', {
      userId,
      prompt,
      type: 'creative'
    }, onMessage, onComplete, onError);
  }

  // 智能推荐 - 流式输出
  async recommendationStream(
    userId: number | string,
    preferences: string,
    onMessage: (content: string) => void,
    onComplete: () => void,
    onError: (error: any) => void
  ): Promise<void> {
    return this.processStream('/api/ai/miniprogram/recommend/stream', {
      userId,
      preferences,
      category: '通用'
    }, onMessage, onComplete, onError);
  }

  // 情感陪伴 - 流式输出
  async emotionalCompanionStream(
    userId: number | string,
    message: string,
    onMessage: (content: string) => void,
    onComplete: () => void,
    onError: (error: any) => void
  ): Promise<void> {
    return this.processStream('/api/ai/miniprogram/emotion/companion/stream', {
      userId,
      message
    }, onMessage, onComplete, onError);
  }

  // 测试连接
  async testConnection(): Promise<boolean> {
    try {
      const response = await fetch(`${this.baseUrl}/api/ai/miniprogram/test`, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
        }
      });
      return response.ok;
    } catch (error) {
      console.error('连接测试失败:', error);
      return false;
    }
  }

  // ==================== 语音通话相关API ====================

  // 获取RTC认证Token
  async getRtcAuthToken(userId: string, channelId?: string): Promise<AiServiceResponse> {
    return this.request('/api/v2/aiagent/getRtcAuthToken', {
      user_id: userId,
      channel_id: channelId
    });
  }

  // 生成AI智能体
  async generateAIAgentCall(userId: string, aiAgentId?: string, region?: string): Promise<AiServiceResponse> {
    return this.request('/api/v2/aiagent/generateAIAgentCall', {
      user_id: userId,
      ai_agent_id: aiAgentId,
      region: region || 'cn-beijing'
    });
  }

  // 描述AI智能体实例
  async describeAIAgentInstance(instanceId: string, userId: string): Promise<AiServiceResponse> {
    return this.request('/api/v2/aiagent/describeAIAgentInstance', {
      ai_agent_instance_id: instanceId,
      user_id: userId
    });
  }

  // 生成消息聊天Token
  async generateMessageChatToken(userId: string, aiAgentId?: string, region?: string): Promise<AiServiceResponse> {
    return this.request('/api/v2/aiagent/generateMessageChatToken', {
      user_id: userId,
      ai_agent_id: aiAgentId,
      region: region || 'cn-beijing'
    });
  }

  // ==================== 删除重复的流式输出API ====================

  // 重复方法已删除，使用processStream版本

  // 重复方法已删除，使用processStream版本

  // streamRequest方法已删除，使用processStream方法
}

// 创建默认实例 - 使用相对路径，通过vite代理转发
const aiService = new AiService('');

export default aiService;
